'''
Created on May 11, 2010

@author: roni
'''
import logging
from projectConstants import ProjectConstants


class AbnormalScenarioGenerator(object):
    '''
    This class creates an abnormal scenario. It is given a scenario and a list of abnormal nodes,
    and creates a new scenario by adding delays to the abnormal nodes.
    '''


    def generateScenario(self,scenario, abnormal_scenario_file_name, abnoramls_to_delay, scenario_file_name=None):
        
        if scenario_file_name is None:
            scenario_file_name = "%s/AbnormalScenarioGenerator.scenario.temp" % ProjectConstants.RESROUCE_DIR
            scenario.save(scenario_file_name)
        
        scenario_file = file(scenario_file_name,'r')
        abnormal_scenario_file = file(abnormal_scenario_file_name,'w')

        # First line should contain the word "nodes"
        line = scenario_file.readline()
        if (line.startswith("nodes")==False):
            raise ValueError('Illegal file format. Expected "nodes"')
        abnormal_scenario_file.write(line)
        
        # Second line should contain the number of nodes
        line = scenario_file.readline()
        abnormal_scenario_file.write(line)
        
        # Third line contains either delays or edges
        line = scenario_file.readline()       
        # Read delays from original scenario and update abnormal delays if needed
        if line.startswith("delays"):
            # Read delays, update according to abnormal delays
            line = scenario_file.readline()
            while line.startswith("edges")==False:
                parts = line.split(",")
                node = int(parts[0].strip())
                delay = int(parts[1].strip())
                if abnoramls_to_delay.has_key(node):
                    abnoramls_to_delay[node]=abnoramls_to_delay[node]+delay
                else:
                    abnoramls_to_delay[node]=delay
                line = scenario_file.readline()
            
        # Write modified delays
        abnormal_scenario_file.write("delays\n")
        for node in abnoramls_to_delay.keys():
            abnormal_scenario_file.write("%d, %d\n" % (node, abnoramls_to_delay[node]))
            logging.info("Added abnormal delay %d ms for node %d" % (abnoramls_to_delay[node],node))            
                
        abnormal_scenario_file.write("edges\n")
        for line in scenario_file.readlines():
            abnormal_scenario_file.write(line)
            
        scenario_file.close()
        abnormal_scenario_file.close()
            
        
        
        
            